#include "Primitive.h"
#include "MyVertex.h"

namespace CAD_CAM
{

	Primitive::Primitive(int verticesCount, int indicesCount)
	{
		init(QVector3D(), QVector3D(1,1,1), verticesCount, indicesCount);
	}

	Primitive::Primitive(QVector3D position, int verticesCount, int indicesCount)
	{
		init(position, QVector3D(1,1,1), verticesCount, indicesCount);
	}

	Primitive::Primitive(QVector3D position, float size, int verticesCount, int indicesCount)
	{
		init(position, QVector3D(size, size, size), verticesCount, indicesCount);
	}

	Primitive::Primitive(float size, int verticesCount, int indicesCount)
	{
		init(QVector3D(), QVector3D(size, size, size), verticesCount, indicesCount);
	}

	void Primitive::init(QVector3D position, QVector3D size, int verticesCount, int indicesCount)
	{
		color = QVector3D(1,1,1);
		mVertexVBO = QGLBuffer(QGLBuffer::VertexBuffer);
		mIndexVBO = QGLBuffer(QGLBuffer::IndexBuffer);

		isInited = false;
		vertices = verticesCount;
		indices = indicesCount;
		sizeScale = size;
		translation = position;

		verticesArray = new MyVertex[vertices];
		indicesArray.reserve(indicesCount);
	}

	Primitive::~Primitive(void)
	{
		mVertexVBO.release();
		mIndexVBO.release();
		delete[] verticesArray;
		mVertexVBO.destroy();
		mIndexVBO.destroy();
	}

	void Primitive::setWidth(double width)
	{
		sizeScale.setX(width);
	}

	void Primitive::setHeight(double height)
	{
		sizeScale.setY(height);
	}

	void Primitive::setLength(double length)
	{
		sizeScale.setZ(length);
	}

	void Primitive::initBuffers(QGLBuffer::UsagePattern usage)
	{
		mVertexVBO.create();
		mIndexVBO.create();

		mVertexVBO.bind();
		mIndexVBO.bind();

		mVertexVBO.setUsagePattern(usage);
		mIndexVBO.setUsagePattern(usage);

		mVertexVBO.allocate(verticesArray, sizeof(MyVertex)*vertices);
		mIndexVBO.allocate(indicesArray.data(), sizeof(GLuint)*indices);
	
		mVertexVBO.release();
		mIndexVBO.release();
		isInited = true;
	}

	void Primitive::setColor(QColor c)
	{
		setColor(QVector3D(c.redF(), c.greenF(), c.blueF()));
	}

	void Primitive::setColor(QVector3D c)
	{
		color = c;
		for(int i =0; i< vertices; ++i)
		{
			verticesArray[i].color = c;
		}

		if(isInited)
		{
			mVertexVBO.bind();
			MyVertex* verticesGPU = (MyVertex*)mVertexVBO.map(QGLBuffer::ReadWrite);
			for(int i =0; i< vertices; ++i)
			{
				verticesGPU[i].color = c;
			}

			mVertexVBO.unmap();
			mVertexVBO.release();
		}
	}


	void Primitive::translate(QVector3D vector)
	{
		translation += vector;
	}
}